import { OpenAI } from "openai"
import { admin } from "./api/index"

chrome.storage.onChanged.addListener((changes) => {
  if (changes.wallpaper) {
    console.log("壁纸已更新:", changes.wallpaper.newValue)
  }
})

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === "UPDATE_WALLPAPER") {
    // 1. 保存到存储
    chrome.storage.local.set({ wallpaper: request.url })

    // 2. 通知所有标签页更新
    // chrome.tabs.query({}, (tabs) => {
    //   tabs.forEach(tab => {
    //     if (tab.id) {
    //       chrome.tabs.sendMessage(tab.id, {
    //         type: "SET_WALLPAPER",
    //         url: request.url
    //       }).catch(err => {
    //         console.log(`标签页 ${tab.id} 注入失败:`, err)
    //       })
    //     }
    //   })
    // })

    // 3. 只通知当前活动的标签页更新
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      const activeTab = tabs[0]
      if (activeTab && activeTab.id) {
        chrome.tabs
          .sendMessage(activeTab.id, {
            type: "SET_WALLPAPER",
            url: request.url
          })
          .catch((err) => {
            console.log(`当前标签页 ${activeTab.id} 注入失败:`, err)
          })
      }
    })
  }
})

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === "DELETE_WALLPAPER") {
    // 1. 同时清除local和sync存储
    // chrome.storage.local.remove('wallpaper', () => {
    chrome.storage.sync.remove("wallpaper", () => {
      // 2. 通知当前活动的标签页更新
      chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs.length > 0 && tabs[0].id) {
          chrome.tabs
            .sendMessage(tabs[0].id, {
              type: "UPDATE_WALLPAPER",
              url: null
            })
            .catch((err) => {
              console.error(`清除标签页 ${tabs[0].id} 壁纸失败:`, err)
            })
        }
      })

      // 3. 发送响应确认操作完成
      sendResponse({ success: true })
    })
    // });

    // 4. 保持消息通道开放
    return true
  }
})

const CURRENT_VERSION = chrome.runtime.getManifest().version;
const VERSION_URL = "http://181898hk44.wicp.vip/api/admin/get/version";
let updateCheckInterval: NodeJS.Timeout | null = null;


// 添加消息监听
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === "STOP_UPDATE_CHECK") {
    console.log("收到停止更新检查请求");
    
    if (updateCheckInterval) {
      clearInterval(updateCheckInterval);
      updateCheckInterval = null;
      console.log("版本更新定时器已停止");
      
      // 可选：发送确认消息回popup
      if (sender.tab) {
        chrome.tabs.sendMessage(sender.tab.id, {
          action: "UPDATE_CHECK_STOPPED"
        }).catch(error => {
          console.log("发送确认消息失败:", error);
        });
      }
    }
    
    sendResponse({ success: true });
    return true;
  }
});
async function checkForUpdate() {
  try {
    const response = await fetch(VERSION_URL);
    const res = await response.json();
    console.log("当前版本:", CURRENT_VERSION);
    const data = res.data;
    console.log("最新版本：", data.version);
    
    if (data.version > CURRENT_VERSION) {
      // 找到Popup页面并发送消息
      chrome.runtime.sendMessage({
        action: "SHOW_UPDATE_NOTIFICATION",
        updateInfo: {
          version: data.version,
          update_log: data.updateLog || "有新版本可用",
          download_url: data.downloadUrl
        }
      }).catch(error => {
        console.log("发送更新消息失败（可能popup未打开）:", error)
      })
      // if (updateCheckInterval) {
      //   clearInterval(updateCheckInterval);
      //   updateCheckInterval = null;
      //   console.log("版本更新定时器停止");
      // }
    }
  } catch (error) {
    console.error("检查更新失败:", error);
    if (updateCheckInterval) {
      clearInterval(updateCheckInterval);
      updateCheckInterval = null;
      console.log("更新检查定时器已停止");
    }
  }
}

// 每小时检查一次更新
updateCheckInterval = setInterval(checkForUpdate, 60 * 1000);
// 插件启动时立即检查一次
checkForUpdate();

const client = new OpenAI({
  baseURL: "https://api-inference.modelscope.cn/v1",
  apiKey: "ms-e8e66448-dd4b-4c88-a98a-cd7d75073362" // ModelScope Token
})

// 处理流式AI请求
chrome.runtime.onConnect.addListener((port) => {
  if (port.name === "deepseek-stream") {
    port.onMessage.addListener(async (request) => {
      if (request.action === "callDeepSeekAIStream") {
        try {
          // 验证并格式化消息
          const validMessages = request.messages.map((msg) => ({
            role: msg.role,
            content:
              typeof msg.content === "string"
                ? msg.content
                : JSON.stringify(msg.content)
          }))

          // 添加系统消息如果不存在
          if (!validMessages.some((msg) => msg.role === "system")) {
            validMessages.unshift({
              role: "system",
              content: "You are a helpful assistant."
            })
          }

          console.log(
            "Sending messages:",
            JSON.stringify(validMessages, null, 2)
          )

          const stream = await client.chat.completions.create({
            // model: "deepseek-ai/DeepSeek-V3",
            model: "deepseek-ai/DeepSeek-R1-0528",
            messages: validMessages,
            stream: true,
            temperature: 0.7,
            max_tokens: 2000
          })

          let fullResponse = ""

          for await (const chunk of stream) {
            const content = chunk.choices[0]?.delta?.content || ""
            if (content) {
              fullResponse += content
              port.postMessage({ chunk: content })
            }
          }

          // 确保发送最后的内容和完成消息
          port.postMessage({
            done: true,
            fullResponse
          })
        } catch (error) {
          console.error("AI服务调用失败:", error)
          const errorMsg = error.response?.data?.error?.message || error.message || "未知错误"
          port.postMessage({
            error: `AI服务调用失败: ${errorMsg}`,
            done: true,
            details: error.response?.data || null
          })
        } finally {
          port.disconnect()
        }
      }
    })

    // 处理端口断开
    port.onDisconnect.addListener(() => {
      console.log("端口已断开")
    })
  }
})
